package org.intelli.dl.learn.order.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.intelli.dl.learn.model.order.Order;
import org.intelli.dl.learn.order.propreties.OrderProperties;
import org.intelli.dl.learn.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: Michael
 * @date: 2025/4/11
 * @desc:
 */
//@RefreshScope
@Slf4j
@RequestMapping("/api/order")
@RestController
public class OrderController {

    @Autowired
    OrderService orderService;

    @Autowired
    private
    OrderProperties orderProperties;

//    @Value("${order.timeout}")
//    String orderTimeout;
//    @Value("${order.auto-confirm}")
//    String orderAutoConfirm;

    @GetMapping("/config")
    public String config(){
        return "orderTimeout: " + orderProperties.getTimeout()
                + ", orderAutoConfirm: " + orderProperties.getAutoConfirm()
                + ", dbUrl: " + orderProperties.getDbUrl();
    }

    // 创建订单
    @GetMapping("/createOrder")
    public Order createOrder(@RequestParam("userId") Long userId,
                             @RequestParam("productId") Long productId){
        return orderService.createOrder(productId, userId);
    }

    @GetMapping("/seckill")
    @SentinelResource(value = "seckill-order", fallback = "seckillFallback")
    public Order seckill(@RequestParam(value = "userId", defaultValue = "888") Long userId,
                             @RequestParam("productId") Long productId){
        Order order = orderService.createOrder(productId, userId);
        order.setId(Long.MAX_VALUE);
        return order;
    }

    public Order seckillFallback(Long userId, Long productId, Throwable exception){
        System.out.println("seckillFallback......");
        Order order = new Order();
        order.setUserId(userId);
        order.setId(productId);
        order.setAddress("异常信息“ " + exception.getClass());
        return order;
    }

    @GetMapping("/writeDb")
    public String writeDb(){
        return "write db success";
    }

    @GetMapping("/readDb")
    public String readDb(){
        log.info("read db");
        return "read db success";
    }
}
